package com.tq.thread;


import lombok.NoArgsConstructor;
import lombok.SneakyThrows;

import java.util.concurrent.*;

/**
 * <a href="https://www.yuque.com/shichuan-hv8di/acr9fp/hb7qi8a2k223rntl?singleDoc#">《📌 Day 1 线程创建》</a>
 *
 * @author TqCoder
 * @since day01
 */
public class Day01 {

    /**
     * 说到底，这几种方式无非都是通过函数式接口，来定义要执行的任务体，然后通过thread类抽象操作系统线程，最后委托给操作系统执行
     * 所有方式最终通过 Thread桥接OS线程，差异仅在于任务封装形式（Runnable/Callable）和线程管理策略（裸线程/线程池/虚拟线程）
     * <p>
     *
     * “一段 Java 代码（任务体）被包装成操作系统认识的线程控制块（TCB），由 OS 调度器真正放到 CPU 上跑。”
     */

    @SneakyThrows
    public static void main(String[] args) {
        // Method 1 Runnable
        new Thread(() -> System.out.println("hello world runnable")).start();

        // Method 2 Extends Thread
        new MyThread().start();

        // Method 3 Callable
        new Thread(new FutureTask<>(() -> "hello world callable")).start();

        // Method 4 Thread Pool
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
        // 提交任务
        threadPoolExecutor.execute(() -> System.out.println("hello world thread pool"));
        Future<String> future = threadPoolExecutor.submit(() -> "hello world thread pool submit");

        String result = future.get(500, TimeUnit.MILLISECONDS);
        System.out.println("线程池任务结果: " + result);
        // 关闭线程池
        threadPoolExecutor.shutdown();
    }

    @NoArgsConstructor
    static class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println("hello world myThread");
        }
    }
}
